package com.gsp.gspframework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public final class ReflectionUtil {
    private static final Logger log = LoggerFactory.getLogger(ReflectionUtil.class);

    public static Object newInstance(Class<?> clz) {
        Object obj;
        try {
            obj = clz.newInstance();
        } catch (InstantiationException e) {
            log.error("new instance error", e);
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            log.error("new instance error", e);
            throw new RuntimeException(e);
        }
        return obj;
    }

    public static Object invoke(Object obj, Method method, Object... args) {
        Object o;
        try {
            method.setAccessible(true);
            o = method.invoke(obj, args);
        } catch (IllegalAccessException e) {
            log.error("method invoke error", e);
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            log.error("method invoke error", e);
            throw new RuntimeException(e);
        }
        return o;
    }

    public static void setField(Object o, Field field,Object value){
        try {
            field.setAccessible(true);
            field.set(o,value);
        } catch (IllegalAccessException e) {
            log.error("set field error", e);
            throw new RuntimeException(e);
        }
    }
}
